package edu.ccut.saturn.studio.logic.model.xml.loader;

import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.ccut.saturn.studio.logic.model.Shape;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnComponentNode;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnParameter;



public class DropComponetLoader extends ComponentNodeLoader {
	private static final String DATABASEFULLKEY = "fullkey";
	private static final String SATURNDATA_NAMESPACE = "namespace";
	private static final String KEY_NODE_NAME = "key";
	private static final String NODE_NAME = "name";
	private static final String PROJECT_NAME_NODE = "projectname";
	private static final String DATA_NAME_NODE = "data";
	public List<Shape> loadNodes(Element root) {
		return super.loadNodes(root);
	}
	
	public Shape getComponet(Element root,Document databaseDoc){
		List<Shape> list = loadNodes(root);
		for(Shape shape : list){
			shape.setNode(null);
			shape.setName(getDropDocumentNodeValue(root,SaturnComponentNode.KEY_NODE_COMPONENT,NODE_NAME));
			String projectName = getDropDocumentNodeValue(root,SaturnComponentNode.KEY_NODE_COMPONENT,PROJECT_NAME_NODE);
			String key = getDropDocumentNodeValue(root,SaturnComponentNode.KEY_NODE_COMPONENT,KEY_NODE_NAME);
			shape.setKey(projectName+"::"+key);
			List<SaturnParameter> parameters = shape.getParameters();
			saturnParameterIsFullKey(parameters,databaseDoc);
			return shape;
		}
		return null;
	}
	
	private void saturnParameterIsFullKey(List<SaturnParameter> parameters,Document databaseDoc){
		for(SaturnParameter parameter : parameters){
			if(parameter.getName().equals(DATABASEFULLKEY)){
				parameter.setValueKey(dataBaseDocumentByKey(databaseDoc));
			}
		}
	}
	
	private String dataBaseDocumentByKey(Document databaseDoc){
		
		String namespace = getDropDocumentNodeValue(databaseDoc.getDocumentElement(),DATA_NAME_NODE,SATURNDATA_NAMESPACE);
		String name = getDropDocumentNodeValue(databaseDoc.getDocumentElement(),DATA_NAME_NODE,NODE_NAME);
		String key = "'"+namespace+"::"+name+"'";
		return key;
		
	}
	
	private String getDropDocumentNodeValue(Element root,String rootNodeName,String nodeName){
		NodeList componentNodes = root.getElementsByTagName(rootNodeName);
		for(int i = 0;i<componentNodes.getLength();i++){
			Node node = componentNodes.item(i);
			return super.getNodeAttributeValue(node, nodeName);
		}
		return null;
	}
	
}
